/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.wx.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.common.utils.EmptyUtil;
import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.web.controller.BaseController;
import com.xdtech.wx.message.resp.TextMessageResp;
import com.xdtech.wx.model.WeixinAccount;
import com.xdtech.wx.service.WechatService;
import com.xdtech.wx.service.WeixinAccountService;
import com.xdtech.wx.util.MessageUtil;
import com.xdtech.wx.util.WeiXinUtils;

/**
 * 微信控制类
 * @author max.zheng
 * @create 2016-3-10下午10:00:45
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
@RequestMapping("/weixin.action")
public class WeChartController extends BaseController{
	@Autowired
	private WeixinAccountService weixinAccountService;
	@Autowired
	private WechatService wechatService;
	
	@RequestMapping(params="wechat", method = RequestMethod.GET)
	public void wechatGet(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "signature") String signature,
			@RequestParam(value = "timestamp") String timestamp,
			@RequestParam(value = "nonce") String nonce,
			@RequestParam(value = "echostr") String echostr) {
				
		List<WeixinAccount> weixinAccounts = weixinAccountService.getAll();
		for (WeixinAccount weixinAccount : weixinAccounts) {
			if (WeiXinUtils.checkSignature(weixinAccount.getToken(), signature, timestamp, nonce)) {
				returnStringContent(request, response, echostr);
				break;
			}
		}
	}
	
	@RequestMapping(params = "wechat", method = RequestMethod.POST)
	@SystemControllerLog(description = "微信反馈")
	public void wechatPost(HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";
//			<xml>
//			 <ToUserName><![CDATA[toUser]]></ToUserName>
//			 <FromUserName><![CDATA[fromUser]]></FromUserName> 
//			 <CreateTime>1348831860</CreateTime>
//			 <MsgType><![CDATA[text]]></MsgType>
//			 <Content><![CDATA[this is a test]]></Content>
//			 <MsgId>1234567890123456</MsgId>
//			 </xml>
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			//发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			//公众帐号
			String toUserName = requestMap.get("ToUserName");
			//消息类型
			String msgType = requestMap.get("MsgType");
			String msgId = requestMap.get("MsgId");
			//消息内容
			String content = requestMap.get("Content");
			//时间
			String createTime = requestMap.get("CreateTime");
			log.info("客户端发送数据：fromUserName:"+fromUserName+"|ToUserName:"+toUserName+"|msgType:"+msgType+"|msgId:"+msgId+"|content:"+content);
			//根据微信ID,获取配置的全局的数据权限ID
//			log.info("-toUserName--------"+toUserName);
//			Long sys_accountId = weixinAccountService.findByAccountId(toUserName).getId();
//			log.info("-sys_accountId--------"+sys_accountId);
			// 默认回复此文本消息
			TextMessageResp textMessage = new TextMessageResp();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(getWelcomeText(toUserName));
			// 将文本消息对象转换成xml字符串
			respMessage = MessageUtil.textMessageToXml(textMessage);
			//【微信触发类型】文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				log.info("------------微信客户端发送请求------------------【微信触发类型】文本消息---");
				respMessage = wechatService.handleTextMsg(fromUserName,toUserName,createTime,msgType,content,msgId,textMessage);
			}
			//【微信触发类型】图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！";
			}
			//【微信触发类型】地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！";
			}
			//【微信触发类型】链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
			}
			//【微信触发类型】音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
			}
			//【微信触发类型】事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				log.info("------------微信客户端发送请求------------------【微信触发类型】事件推送---");
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					respMessage = "订阅";//doDingYueEventResponse(requestMap, textMessage, bundler, respMessage, toUserName, fromUserName, respContent, sys_accountId);
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					respMessage = "菜单";//doMyMenuEvent(requestMap, textMessage, bundler, respMessage, toUserName, fromUserName, respContent, sys_accountId, request);
				}
			}
		} catch (Exception e) {
			log.error("消息处理异常",e);
//			respMessage = "Sorry Error";
		}
		returnStringContent(request, response, respMessage);
	}
	
	
	/**
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2016-3-11 下午2:11:13
	 * @param toUserName
	 * @return
	 */
	private String getWelcomeText(String toUserName)
	{
		WeixinAccount weixinAccount = weixinAccountService.findByAccountId(toUserName);
		if (EmptyUtil.isNotEmpty(weixinAccount.getWelcomeText()))
		{
			return weixinAccount.getWelcomeText();
		}
		return MessageUtil.WELCOME_TEXT;
	}

	/**
	 * 针对文本消息
	 * @param content
	 * @param toUserName
	 * @param textMessage
	 * @param bundler
	 * @param sys_accountId
	 * @param respMessage
	 * @param fromUserName
	 * @param request
	 * @throws Exception 
	 */
//	String doTextResponse(String content,String toUserName,TextMessageResp textMessage,ResourceBundle bundler,
//			String sys_accountId,String respMessage,String fromUserName,HttpServletRequest request,String msgId,String msgType) throws Exception{
//		//=================================================================================================================
//		// 保存接收到的信息
//		ReceiveText receiveText = new ReceiveText();
//		receiveText.setContent(content);
//		Timestamp temp = Timestamp.valueOf(DateUtils
//				.getDate("yyyy-MM-dd HH:mm:ss"));
//		receiveText.setCreateTime(temp);
//		receiveText.setFromUserName(fromUserName);
//		receiveText.setToUserName(toUserName);
//		receiveText.setMsgId(msgId);
//		receiveText.setMsgType(msgType);
//		receiveText.setResponse("0");
//		receiveText.setAccountId(toUserName);
//		this.receiveTextService.save(receiveText);
//		//=================================================================================================================
//		//Step.1 判断关键字信息中是否管理该文本内容。有的话优先采用数据库中的回复
//		log.info("------------微信客户端发送请求--------------Step.1 判断关键字信息中是否管理该文本内容。有的话优先采用数据库中的回复---");
//		AutoResponse autoResponse = findKey(content, toUserName);
//		// 根据系统配置的关键字信息，返回对应的消息
//		if (autoResponse != null) {
//			String resMsgType = autoResponse.getMsgType();
//			if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(resMsgType)) {
//				//根据返回消息key，获取对应的文本消息返回给微信客户端
//				TextTemplate textTemplate = textTemplateDao.getTextTemplate(sys_accountId, autoResponse.getTemplateName());
//				textMessage.setContent(textTemplate.getContent());
//				respMessage = MessageUtil.textMessageToXml(textMessage);
//			} else if (MessageUtil.RESP_MESSAGE_TYPE_NEWS.equals(resMsgType)) {
//				List<NewsItem> newsList = this.newsItemService.findByProperty(NewsItem.class,"newsTemplate.id", autoResponse.getResContent());
//				NewsTemplate newsTemplate = newsTemplateService.getEntity(NewsTemplate.class, autoResponse.getResContent());
//				List<Article> articleList = new ArrayList<Article>();
//				for (NewsItem news : newsList) {
//					Article article = new Article();
//					article.setTitle(news.getTitle());
//					article.setPicUrl(bundler.getString("domain") + "/"+ news.getImagePath());
//					String url = "";
//					if (oConvertUtils.isEmpty(news.getUrl())) {
//						url = bundler.getString("domain")+ "/newsItemController.do?newscontent&id="+ news.getId();
//					} else {
//						url = news.getUrl();
//					}
//					article.setUrl(url);
//					article.setDescription(news.getDescription());
//					articleList.add(article);
//				}
//				NewsMessageResp newsResp = new NewsMessageResp();
//				newsResp.setCreateTime(new Date().getTime());
//				newsResp.setFromUserName(toUserName);
//				newsResp.setToUserName(fromUserName);
//				newsResp.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
//				newsResp.setArticleCount(newsList.size());
//				newsResp.setArticles(articleList);
//				respMessage = MessageUtil.newsMessageToXml(newsResp);
//			}
//		} else {
//			// Step.2  通过微信扩展接口（支持二次开发，例如：翻译，天气）
//			log.info("------------微信客户端发送请求--------------Step.2  通过微信扩展接口（支持二次开发，例如：翻译，天气）---");
//			List<WeixinExpandconfigEntity> weixinExpandconfigEntityLst = weixinExpandconfigService.findByQueryString("FROM WeixinExpandconfigEntity");
//			if (weixinExpandconfigEntityLst.size() != 0) {
//				for (WeixinExpandconfigEntity wec : weixinExpandconfigEntityLst) {
//					boolean findflag = false;// 是否找到关键字信息
//					// 如果已经找到关键字并处理业务，结束循环。
//					if (findflag) {
//						break;// 如果找到结束循环
//					}
//					String[] keys = wec.getKeyword().split(",");
//					for (String k : keys) {
//						if (content.indexOf(k) != -1) {
//							String className = wec.getClassname();
//							KeyServiceI keyService = (KeyServiceI) Class.forName(className).newInstance();
//							respMessage = keyService.excute(content,textMessage, request);
//							findflag = true;// 改变标识，已经找到关键字并处理业务，结束循环。
//							break;// 当前关键字信息处理完毕，结束当前循环
//						}
//					}
//				}
//			}
//
//		}
//		return respMessage;
//	}
}
